package cn.wit.summit.chwan.ui.activity;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.models.dto.GameTypeBean;
import cn.wit.summit.chwan.models.event.NotNetEvent;
import cn.wit.summit.chwan.models.response.GameTypeListResponse;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.ui.base.BaseActivity;
import cn.wit.summit.chwan.utils.IntentUtil;
import cn.wit.summit.chwan.utils.MyImageLoader;
import cn.wit.summit.chwan.utils.NetWorkUtils;
import cn.wit.summit.chwan.utils.PreferenceUtil;
import cn.wit.summit.chwan.widgets.refreshLayout.SmartRefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.api.RefreshLayout;
import retrofit2.Retrofit;

public class GameTypeListActivity extends BaseActivity {

    @Bind(R.id.bar_title_tx)
    TextView           barTitleTx;
    @Bind(R.id.recyclerView)
    RecyclerView       recyclerView;
    @Bind(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    private GameAdapter adapter;

    //src
    private List<GameTypeBean> datas = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game_type_list);
        ButterKnife.bind(this);
        initApi();
        if (barTitleTx != null)
            barTitleTx.setText("分类");

        initRecyclerView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void initRecyclerView() {
        adapter = new GameAdapter(this, datas);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        recyclerView.setFocusable(false);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setOnRefreshListener(new cn.wit.summit.chwan.widgets.refreshLayout.listener.OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                GameTypeListActivity.this.onRefresh();
            }
        });
        refreshLayout.setOnLoadMoreListener(new cn.wit.summit.chwan.widgets.refreshLayout.listener.OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                GameTypeListActivity.this.onLoadMore();
            }
        });
        //触发自动刷新
        refreshLayout.autoRefresh();
    }

    void loadGameTypeList() {
        api.getGameTypeList().enqueue(new MyCallback<ResponseBase<GameTypeListResponse>>() {
            @Override
            public void onSuccess(ResponseBase<GameTypeListResponse> model) {
                if (model != null) {
                    if (model.getCode() == 600)
                        onResponse(model.getData_info());
                    else
                        onFailure(model.getCode(), model.getMsg());
                } else {
                    onFailure(-1, "服务器数据为空！");
                }

            }

            @Override
            public void onFailure(int code, String msg) {
                onFailure(new Exception(msg), code);
            }

            public void onResponse(GameTypeListResponse data) {
                cancelLoadingFinish();
                PreferenceUtil.savePreference(GameTypeListActivity.this, "game_type_list", new Gson().toJson(data));
                if (data != null && data.getGame_type() != null) {
                    datas.clear();
                    datas.addAll(data.getGame_type());
                }
                notifyTagChanged();
                stopLoading();
            }

            public void onFailure(Exception e, int code) {
                cancelLoadingError();
                stopLoading();
                showToast(e.getMessage());
            }
        });
    }

    void notifyTagChanged() {
        adapter.notifyDataSetChanged();
    }


    private void stopLoading() {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        adapter.notifyDataSetChanged();
    }

    public void onRefresh() {
        loadGameTypeList();
    }

    public void onLoadMore() {
        loadGameTypeList();
    }

    //endregion

    private static class GameAdapter extends RecyclerView.Adapter implements View.OnClickListener {
        private List<GameTypeBean> datas;
        Context context;

        public GameAdapter(Context context, List<GameTypeBean> datas) {
            this.context = context;
            this.datas = datas;
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            if (viewType == 0) {

                View view = new View(context);
//        View                      view1  = new View(this);
                int                       width  = ViewGroup.LayoutParams.MATCH_PARENT;
                int                       height = (int) context.getResources().getDimension(R.dimen.wdp19);
                RecyclerView.LayoutParams lp     = new RecyclerView.LayoutParams(width, height);
                view.setLayoutParams(lp);

                return new ItemHeader(view);
            }
            return new ItemGameType(LayoutInflater.from(context).inflate(R.layout.item_game_type_list, parent, false));
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            if (holder == null) return;
            if (getItemViewType(position) == 0) {
                return;
            }
            ItemGameType itemGameType = (ItemGameType) holder;

            if (position == 1) {
                itemGameType.divider.setVisibility(View.GONE);
            } else {
                if (itemGameType.divider.getVisibility() != View.VISIBLE)
                    itemGameType.divider.setVisibility(View.VISIBLE);
            }

            MyImageLoader.load(itemGameType.icon, getItem(position).getGame_ico());
            itemGameType.name.setText(getItem(position).getGame_type_name());

            holder.itemView.setTag(position);
            holder.itemView.setOnClickListener(this);
        }

        @Override
        public int getItemViewType(int position) {
            if (position == 0 || position == datas.size() + 1) return 0;
            return 1;
        }

        public GameTypeBean getItem(int position) {
            if (datas == null) return null;
            if (position == 0 || position == datas.size() + 1) return null;
            return datas.get(position - 1);
        }

        @Override
        public int getItemCount() {
            if (datas == null) return 0;
            return datas.size() + 2;
        }

        @Override
        public void onClick(View v) {
            GameTypeBean bean = getItem((Integer) v.getTag());
            IntentUtil.getInstance().goGameListIndex(v.getContext(), bean.getGame_type_id(), bean.getGame_type_name());
        }

        private class ItemHeader extends RecyclerView.ViewHolder {

            public ItemHeader(View itemView) {
                super(itemView);
            }
        }

        private class ItemGameType extends RecyclerView.ViewHolder {
            SimpleDraweeView icon;
            TextView         name;
            View             divider;

            public ItemGameType(View inflate) {
                super(inflate);
                divider = inflate.findViewById(R.id.divider);
                icon = inflate.findViewById(R.id.icon);
                name = inflate.findViewById(R.id.name);
            }
        }
    }

    @OnClick(R.id.back)
    void back() {
        finish();
    }

    @Override
    public void reGetData() {
        if (NetWorkUtils.isNetworkConnected(this))
            onRefresh();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(NotNetEvent notNetEvent) {
        if (!notNetEvent.isHasNet
                && datas != null && datas.size() > 0) return;
        super.onEventMainThread(notNetEvent);
    }

    //region Retrofit
    private RetrofitManager retrofitManager;
    private Retrofit        retrofit;
    private ApiUtil         api;

    void initApi() {
        if (retrofitManager == null) {
            retrofitManager = RetrofitManager.getInstance(this);
            retrofit = retrofitManager.getRetrofit();
            api = retrofit.create(ApiUtil.class);
        }
    }
    //endregion
}
